﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CardInChina.Web.Mvc
{
    public class SessionAuthorizeAttribute : AuthorizeAttribute
    {
        private User user = new User();


        public bool RequireEmailVerify { get; set; }
        public bool RequireActivate { get; set; }
        public bool RequirePaypalVerify { get; set; }
        public bool RequireVIP { get; set; }

        public SessionAuthorizeAttribute()
        {
            RequireEmailVerify = true;
        }


        //public static string sessionKey = "CurUser";
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }

            if (!user.IsLogon)
                return false;

            else if (RequireEmailVerify && !user.Details.Entity.EmailConfirmed)
                return false;

            else if (RequireActivate && !user.Details.Entity.IsActivated)
                return false;

            else if (RequirePaypalVerify && !user.Details.Entity.HasPaypalAccount)
                return false;

            else if (RequireVIP && !user.Details.Entity.IsVipCustomer)
                return false;

            return true;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            //MVC默认使用401，并且利用ASP.NET的机制302到web.config配置的页面，这里重写了HttpUnauthorizedResult，直接302
            //filterContext.Result = new HttpUnauthorizedResult();

            if (!user.IsLogon)
                filterContext.Result = new RedirectToLoginResult();

            else if (RequireEmailVerify && !user.Details.Entity.EmailConfirmed)
                filterContext.Result = new RedirectToEmailVerifyResult();

            else if (RequireActivate && !user.Details.Entity.IsActivated)
                throw new NotImplementedException();

            else if (RequirePaypalVerify && !user.Details.Entity.HasPaypalAccount)
                throw new NotImplementedException();

            else if (RequireVIP && !user.Details.Entity.IsVipCustomer)
                throw new NotImplementedException();

        }
    }
}